package com.zdxlz.fcmp.common.core.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import com.zdxlz.fcmp.common.core.exception.BizException;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author: aman
 * @date 2025/2/11 15:54
 * @description
 */

@Slf4j
public class JsonUtil {
    private static final ObjectMapper objectMapper;
    static {
        objectMapper = new ObjectMapper();
        // 配置序列化和反序列化特性
        // 忽略未知属性，避免反序列化时因存在未知属性而抛出异常
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 允许单引号
        objectMapper.configure(com.fasterxml.jackson.core.JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        // 忽略空对象的序列化
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    }
    // 将对象转换为 JSON 字符串
    public static String toJson(Object object) {
        if (object == null) {
            throw new BizException("Object to be converted cannot be null.");
        }
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            log.error("Failed to convert object to JSON string. Object type: {}", object.getClass().getName(), e);
            throw new BizException("Failed to convert object to JSON string.");
        }
    }
    // 将 JSON 字符串转换为指定类型的对象
    public static <T> T fromJson(String json, Class<T> clazz) {
        if (json == null || clazz == null) {
            throw new BizException("Object to be converted cannot be null.");
        }
        try {
            return objectMapper.readValue(json, clazz);
        } catch (JsonProcessingException e) {
            log.error("Failed to convert JSON string to object. Target class: {}", clazz.getName(), e);
            throw new BizException("Failed to convert JSON string to object.");
        }
    }
    // 从 JSON 字符串转换为对象（带更复杂类型支持）
    public static <T> T fromJson(String json, TypeReference<T> typeReference) {
        if (json == null || typeReference == null) {
            throw new BizException("Object to be converted cannot be null.");
        }
        try {
            return objectMapper.readValue(json, typeReference);
        } catch (IOException e) {
            log.error("Failed to convert JSON string to object using TypeReference. Type reference: {}", typeReference.getType(), e);
            throw new BizException("Failed to convert JSON string to object using TypeReference.");
        }
    }
    // 判断一个字符串是否是有效的 JSON 格式
    public static boolean isValidJson(String json) {
        if (json == null) {
            return false;
        }
        try {
            objectMapper.readTree(json);
            return true;
        } catch (JsonProcessingException e) {
            log.debug("The provided string is not a valid JSON: {}", json, e);
            throw new BizException("Invalid JSON format");
        }
    }

    // 获取 JsonNode 根节点
    public static JsonNode getJsonRootNode(String json) {
        if (json == null) {
            throw new BizException("Object to be converted cannot be null.");
        }
        try {
            return objectMapper.readTree(json);
        } catch (JsonProcessingException e) {
            log.error("Failed to parse JSON string to JsonNode. JSON: {}", json, e);
            throw new BizException("Failed to parse JSON string to JsonNode.");
        }
    }


    /**
     * 从 Map 中获取指定键的 List
     *
     * @param resultMap 传入的 result 部分
     * @param key       要提取的键
     * @param clazz     List 中元素的类型
     * @param <T>       List 中元素的类型参数
     * @return 对应的 List，如果不存在则返回 null
     */
    public static <T> List<T> getListFromMap(Map<String, Object> resultMap, String key, Class<T> clazz) {
        try {
            // 获取指定键的对象
            Object listObject = resultMap.get(key);

            if (listObject != null) {
                // 将对象转换为 JSON 字符串
                String listJson = objectMapper.writeValueAsString(listObject);

                // 反序列化为指定类型的 List
                return objectMapper.readValue(listJson, objectMapper.getTypeFactory().constructCollectionType(List.class, clazz));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    // 获取 ObjectMapper 实例，方便外部进行更高级的配置
    public static ObjectMapper getObjectMapper() {
        return objectMapper;
    }
}
